﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebShop.DataService;

namespace WebShop.Classes.DataSource.Driver
{
    public class Mock : IDataSource
    {
        private string m_language;
        private List<User> m_users = new List<User>();

        public Mock(string language)
        {
            m_language = language;
        }

        /// <summary>
        /// Load categories list from datasource
        /// </summary>
        /// <param name="parentId">Parent category Id</param>
        /// <returns></returns>
        public List<DataService.CategoryView> GetCategories(int parentId = 0)
        {
            List<DataService.CategoryView> result = new List<CategoryView>();

            int max = 8;

            string name = "";
            switch (m_language)
            {
                case "eng":
                    name = "Category";
                    break;
                case "rus":
                    name = "Категория";
                    break;
            }

            if (parentId <= max)
            {
                for (int i = 1; i <= max; i++)
                {
                    result.Add(new CategoryView()
                    {
                        Id = (parentId == 0) ? i : (i + max),
                        ParentId = parentId,
                        Image = "/static/mock/categories/test-" + i + ".jpg",
                        Name = (parentId == 0) ? (name + " " + i) : (name + " " + i + " - " + parentId),
                    });
                }
            }

            return result;
        }


        /// <summary>
        /// Load category info
        /// </summary>
        /// <param name="id">category id</param>
        /// <returns>null if we have no category with this id</returns>

        public DataService.CategoryView GetCategory (int id)
        {
            DataService.CategoryView result = null;

            string name = "";
            switch (m_language)
            {
                case "eng":
                    name = "Category";
                    break;
                case "rus":
                    name = "Категория";
                    break;
            }

            result = new CategoryView()
            {
                Id = id,
                Name = name + " " + id,
                ParentId = 1
            };

            return result;
        }


        public List<ProductView> GetCategoryProducts(int categoryId, int page = 0, ProductSort sort = ProductSort.NameAsc, Dictionary<ProductFilter, object> filter = null, int placeid = 0)
        {
            List<ProductView> result = new List<ProductView>();

            int max = 25;
            
            //int min_price = (filter != null && filter.ContainsKey("min_price")) ? (int)filter["min_price"] : 0;
            //int max_price = (filter != null && filter.ContainsKey("max_price")) ? (int)filter["max_price"] : 0;

            string name = "";
            switch (m_language)
            {
                case "eng":
                    name = "Item";
                    break;
                case "rus":
                    name = "Предмет";
                    break;
            }

            for (int i = 1; i <= max; i++)
            {
                int id = i + ((page == 0) ? 0 : (page - 1));
                int price = id * 100;
                /*int price = min_price + id * 100;
                if (max_price != 0 && price > max_price)
                {
                    price = max_price;
                }*/
                ProductView item = new ProductView()
                                        {
                                            Id = id,
                                            Name = name + " " + id,
                                            Count = 10,
                                            Price = price,
                                        };
                result.Add(item);
            }

            if (sort != ProductSort.PriceAsc && sort != ProductSort.NameAsc)
            {
                result.Reverse();
            }

            return result;

        }


        public int GetCategoryPages(int categoryId)
        {
            return 10;
        }


        public ProductFull GetProduct(long id)
        {

            List<string> gallery = new List<string>();
            for (int i = 0; i < 15; i++)
            {
                gallery.Add("/static/mock/product/280x280.rb.gif");
            }

            string name = "";
            string description = "";
            switch (m_language)
            {
                case "eng":
                    name = "Item";
                    description = @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
                    break;
                case "rus":
                    name = "Предмет";
                    description = @"Бозе-конденсат, на первый взгляд, выталкивает термодинамический квант даже в случае сильных локальных возмущений среды. Сверхпроводник устойчив в магнитном поле. В ряде недавних экспериментов возмущение плотности испускает погранслой - все дальнейшее далеко выходит за рамки текущего исследования и не будет здесь рассматриваться. Частица, в первом приближении, катастрофично концентрирует квант только в отсутствие тепло- и массообмена с окружающей средой. Поверхность, как можно показать с помощью не совсем тривиальных вычислений, едва ли квантуема. Кристалл представляет собой разрыв в том случае, когда процессы переизлучения спонтанны. ";
                    break;
            }

            ProductFull result = new ProductFull()
            {
                Id = id,
                Count = 10,
                Description = description,
                Name = name + " " + id,
                Price = id * 100,
                Gallery = gallery,
                Photo = "/static/mock/product/280x280.rb.gif",
                CategoryId = 1,
            };

            return result;
        }


        public Dictionary<string, string> GetLanguages()
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            result.Add("rus", "Русский");
            result.Add("eng", "English");

            return result;
        }


        public User GetUser(string login, string password)
        {
            User result = null;

            if (login == "111" && password == "222")
            {
                result = new User()
                {
                    Id = 0,
                    Email = "333",
                    FIO = "444",
                    Login = "111",
                    Password = "222",
                    Phone = "555",
                    PlaceId = null,
                    Role = UserRole.Guest
                };
            }

            return result;
        }

        public User SetUser(User user)
        {
            User result = null;

            if (GetUser(user.Login, user.Password) == null)
            {
                if (user.Id == 0)
                {
                    user.Id = m_users.Count;
                    m_users.Add(user);
                }
                else
                {
                    m_users[(int)(user.Id - 1)] = user;
                }

                result = user;
            }

            return result;
        }


        public User GetUser(long userid)
        {
            User result = null;

            result = new User()
            {
                Id = userid,
                Email = "333",
                FIO = "444",
                Login = "111",
                Password = "222",
                Phone = "555",
                PlaceId = null,
                Role = UserRole.Guest
            };

            return result;
        }

        public List<PlaceView> GetPlaces()
        {
            List<PlaceView> result = new List<PlaceView>();

            string name = "";
            string address = "";

            switch (m_language)
            {
                case "eng":
                    name = "Place ";
                    address = @"Address ";
                    break;
                case "rus":
                    name = "Магазин ";
                    address = @"Адрес ";
                    break;
            }

            for (int i = 1; i <= 5; i++)
            {
                result.Add(new PlaceView()
                {
                    Id = i,
                    Name = name + i,
                    Address = address + i
                });
            }
            return result;
        }


        public OrderFull SetOrder(OrderFull order)
        {
            order.Id = 1;
            return order;
        }


        public List<OrderView> GetOrders()
        {
            List<OrderView> result = new List<OrderView>();

            for (int i = 1; i <= 4; i++)
            { 
                result.Add(new OrderView()
                {
                    CreatedDateTime = DateTime.Now,
                    Id = i,
                    Price = i * 100,
                    Status = (OrderStatus)i
                });
            }

            return result;
        }


        public OrderFull GetOrder(long id)
        {
            List<OrderPosition> composition = new List<OrderPosition>();


            for (int i=1;i<=5;i++){
                string name = "";
                switch (m_language)
                {
                    case "eng":
                        name = "Item ";
                        break;
                    case "rus":
                        name = "Предмет ";
                        break;
                }

                composition.Add(new OrderPosition(){
                    Cost = id * 100,
                    Count = 1,
                    Product = new ProductView()
                    {
                        CategoryId = 1,
                        Count = 1,
                        Id = id+1,
                        Name = name + i
                    }
                });

            }

            return new OrderFull(){
                Id = id,
                CreatedDateTime = DateTime.Now,
                PlaceId = 1,
                Status = OrderStatus.Created,
                Composition = composition 
            };
        }
    }
}